直到昨天終於寫到 Interface 了
所以就可以利用 Mockery 來寫測試了
所以今天就來重構一下 CartTest 吧
首先先安裝 mockery
composer require mockery/mockery --dev
接下來就來修改 CartTest 吧
// tests/CartTest.php
namespace Recca0120\Cart\Tests;
use Mockery as m;
use Recca0120\Cart\Cart;
use Recca0120\Cart\Item;
use Recca0120\Cart\Store;
use PHPUnit\Framework\TestCase;
use Mockery\Adapter\Phpunit\MockeryPHPUnitIntegration;
class CartTest extends TestCase
{
use MockeryPHPUnitIntegration;
/** @test */
public function 將商品加入購物車並驗證商品有名稱單價數量()
{
$item = $this->createItem('商品01', 100, 1);
$store = m::mock(Store::class);
$store->shouldReceive('put')->with($item)->once();
$cart = new Cart($store);
$cart->put($item);
}
/** @test */
public function 加總()
{
$store = m::mock(Store::class);
$store->shouldReceive('items')->once()->andReturnUsing(function () {
return [
$this->createItem('商品01', 100, 2),
$this->createItem('商品02', 200, 1),
];
});
$cart = new Cart($store);
$this->assertEquals(400, $cart->total());
}
/** @test */
public function 移除商品()
{
$item = $this->createItem('商品01', 100, 2);
$store = m::mock(Store::class);
$store->shouldReceive('remove')->once()->with($item);
$cart = new Cart($store);
$cart->remove($item);
}
private function createItem($name, $price, $qty)
{
return new Item([
'name' => $name,
'price' => $price,
'quantity' => $qty,
]);
}
}